//
//  CBRegularExpressionManager.m
//  CBEmotionView
//
//  Created by ly on 8/21/13.
//  Copyright (c) 2013 ly. All rights reserved.
//

#import "CBRegularExpressionManager.h"
#import "CHEmotionHelper.h"

@implementation CBRegularExpressionManager

+ (NSArray *)itemIndexesWithPattern:(NSString *)pattern inString:(NSString *)findingString
{
    if(findingString == nil || pattern == nil)return nil;
    NSAssert(pattern != nil, @"%s: pattern 不可以为 nil", __PRETTY_FUNCTION__);
    NSAssert(findingString != nil, @"%s: findingString 不可以为 nil", __PRETTY_FUNCTION__);
    
    NSError *error = nil;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    CHEmotionHelper *helper = [CHEmotionHelper sharedInstance];
    // 查找匹配的字符串
    if (error) {
        //NSLog(@"ERROR:%@",error);
        return nil;
    }
    
    NSMutableArray *ranges = [[NSMutableArray alloc] init];
    
    NSRange searchRange = NSMakeRange(0, [findingString length]);
    
    [regExp enumerateMatchesInString:findingString options:0 range:searchRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        NSString *str = [findingString substringWithRange:result.range];
        if ([helper findEmotionByText:str])
        {
            [ranges addObject:[NSValue valueWithRange:result.range]];
        }
    }];
    NSUInteger count = [ranges count];
    // 没有查找到结果，返回空数组
    if (0 == count) {
        //NSLog(@"-------ranges count:0-------");
        return [NSArray array];
    }
    //NSLog(@"-------ranges count:%d-------",[ranges count]);
    return ranges ;
}

@end
